package com.robusta.cityuate.services;

import java.io.UnsupportedEncodingException;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;

import com.robusta.cityuate.R;
import com.robusta.cityuate.objects.User;
import com.robusta.cityuate.utils.ConnectionUtils;

public class ForgetPasswordService extends HTTPService {

	private static final String REQUEST_URL = "/registrations/forgot_password";
	private Context mContext = this;

	@Override
	protected void onResponse() {
		Intent loginUIupdate = new Intent(assignedFilter);
		//Log.d(TAG, "AssignedFilter= " + assignedFilter);
		switch (responseStatusCode) {
		case HttpStatus.SC_NO_CONTENT: {// successful login
								// remove connection from shared pref
			ConnectionUtils.setDisconnecting(mContext, true, assignedFilter,
					null);

			// update UI if active
			loginUIupdate.putExtra(RESUlT, true);
			break;
		}
		case HttpStatus.SC_UNPROCESSABLE_ENTITY: {
			// extract the message
			//JSONObject responseMsg;
			String msg = null;
			//try {
				//responseMsg = new JSONObject(responseString);
				//msg = responseMsg.getJSONArray(HTTPService.MESSAGE).getString(0);
				msg = getString(R.string.mail_not_found);
			//} catch (JSONException e) {
				//e.printStackTrace();
			//}
			// remove connection from shared pref
			ConnectionUtils.setDisconnecting(mContext, false, assignedFilter,
					msg);
			// update UI if active
			loginUIupdate.putExtra(RESUlT, false);
			//Log.d(TAG, "loginFailed" + msg);
		}

		}
		sendOrderedBroadcast(loginUIupdate, null);

	}

	@Override
	protected void onNoResponse(String msg) {
		// remove connection from shared pref keeping result and reason
		ConnectionUtils.setDisconnecting(mContext, false, assignedFilter, msg);
		// update UI if active
		Intent loginUIupdate = new Intent(assignedFilter);
		loginUIupdate.putExtra(RESUlT, false);
		sendOrderedBroadcast(loginUIupdate, null);

	}

	@Override
	protected HttpRequestBase initRequest() {
		HttpPost req = new HttpPost(API_URL + REQUEST_URL);
		try {
			req.setEntity(createPostBody());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return req;
	}

	/**
	 * creates the body of the request from parameters
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private ByteArrayEntity createPostBody()
			throws UnsupportedEncodingException {
		// Creating Body
		JSONObject user = new JSONObject();
		try {
			JSONObject bodyData = new JSONObject();
			bodyData.put(User.USER_EMAIL, extras.get(User.USER_EMAIL));
			user.put(User.USER, bodyData);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return new ByteArrayEntity(user.toString().getBytes("UTF-8"));
	}

}
